<?php
/**
 *  Component: JUser - Extends Jomla registration
 *  Author: http://joomlaequipment.com
 *  license: commercial http://joomlaequipment.com/content/view/10/42/
 *  version: 1.0.6
 */
error_reporting(E_ALL ^ E_NOTICE);
defined( '_VALID_MOS' ) or die( 'Restricted access' );
if (!$acl->acl_check( 'administration', 'manage', 'users', $my->usertype, 'components', 'com_users' )) {
	mosRedirect( 'index2.php', _NOT_AUTH );
}


if(!class_exists('JEConfig'))
	require_once( $mosConfig_absolute_path . '/administrator/components/com_juser/joomlaequipment.config.php' );

if(file_exists($mosConfig_absolute_path ."/administrator/components/com_juser/update.php"))
	include_once($mosConfig_absolute_path ."/administrator/components/com_juser/update.php");

if(file_exists($mosConfig_absolute_path ."/administrator/components/com_juser/additional_data.php"))
	include_once($mosConfig_absolute_path ."/administrator/components/com_juser/additional_data.php");

if(file_exists($mosConfig_absolute_path ."/administrator/components/com_juser/language/{$mosConfig_lang}.php")){
	include_once( $mosConfig_absolute_path ."/administrator/components/com_juser/language/{$mosConfig_lang}.php" );
}
else{
	include_once( $mosConfig_absolute_path ."/administrator/components/com_juser/language/english.php" );
}
if($task != 'export_file' )
{
	if(is_dir($mosConfig_absolute_path."/administrator/components/com_jcs")){
		require_once( $mosConfig_absolute_path . '/administrator/components/com_juser/xajax_functions.php' );
	}
}

if(file_exists($mosConfig_absolute_path ."/administrator/components/com_juser/validate_email.php"))
	include_once($mosConfig_absolute_path ."/administrator/components/com_juser/validate_email.php");

require_once( $mosConfig_absolute_path."/includes/domit/xml_domit_lite_parser.php" );

require_once($mosConfig_absolute_path.'/administrator/components/com_installer/installer.class.php');

require_once( $mainframe->getPath( 'admin_html' ) );
require_once( $mainframe->getPath( 'class' ) );


/*$xml = new integration_XML(6);
print'<pre>';print_r($xml->getFieldList());print'</pre>';*/



$cid	= mosGetParam( $_REQUEST, 'cid' );
if( !is_array( $cid ) ) {$cid = array(0);}

if( file_exists ( $mosConfig_absolute_path ."/administrator/components/com_juser/admin.juser.pro.php" ) )
	include_once( $mosConfig_absolute_path ."/administrator/components/com_juser/admin.juser.pro.php" );

switch ($task) {
	case 'export_file':
   include($mosConfig_absolute_path.'/administrator/components/com_juser/export_table_data_xls.php');
    break;

  case 'exportUser':
		$query = "SELECT #__extending_field_list. * , #__extending_field_list.id as field_id, #__categories.title as cat_title"
			. "\n FROM #__extending_field_list"
			. "\n LEFT JOIN #__categories ON #__categories.id = #__extending_field_list.catid"
			. "\n WHERE #__extending_field_list.published = 1"
			. "\n ORDER by #__categories.ordering, #__extending_field_list.ordering"
		;
		$database->setQuery( $query );
		$ext_rows = $database->loadObjectList();
		HTML_JUser::exportUser($ext_rows);
		break;
	case 'export_execute':
		$query = "SELECT #__extending_field_list. * , #__extending_field_list.id as field_id, #__categories.title as cat_title"
			. "\n FROM #__extending_field_list"
			. "\n LEFT JOIN #__categories ON #__categories.id = #__extending_field_list.catid"
			. "\n WHERE #__extending_field_list.published = 1"
			. "\n ORDER by #__categories.ordering, #__extending_field_list.ordering"
		;
		$database->setQuery( $query );
		$ext_rows = $database->loadObjectList();
		export_execute($ext_rows);
		break;
	case 'report':
		$query = "SELECT #__extending_field_list.*"
			. "\n FROM `#__extending_field_list`"
			. "\n where (`type`='select' OR `type`='checkbox' OR `type`='radio') AND `published` = 1";
		$database->setQuery( $query );
		$fields = $database->loadObjectList();
		HTML_JUser::report_configuration($fields);
		break;
	case 'report_execute':
		//print'<pre>';print_r($_POST);print'</pre>';
		JUser::report_execute();
		break;
	case 'report_for_print':
		JUser::report_execute();
		break;
	case 'savecnf':
	case 'applycnf':
		JEConfig::save();
		break;
	case 'config':
		JEConfig::renderForm(1);
		break;
	case 'savefield':
		JUser::saveField($option);
		break;
	case 'canselfield':
		mosRedirect( 'index2.php?option='. $option .'&task=extend_fields' );
		break;
	case 'updatefield':
		JUser::updateField($option);
		break;
	case 'editfield':
		editField();
		break;
	case 'new_field':
    editField('new');
		/*$query = "SELECT * FROM `#__categories` where `section` = 'com_extending_field_list'";
		$database->setQuery( $query );
		$categories= $database->loadObjectList();
		HTML_JUser::editField( array(),$categories, mosGetParam( $_REQUEST, 'suggestion', '' ) );*/
		break;
	case 'delete_fields':
		JUser::deleteFields( $cid, $option );
		break;
	case 'hide_fields':
		JUser::publishFields( $cid, $option, 0 );
		break;
	case 'publish_fields':
		JUser::publishFields( $cid, $option, 1 );
		break;
	case 'orderup':
	case 'orderdown':
		orderField( intval( $cid[0] ), ($task == 'orderup' ? -1 : 1), $option );
		break;
	case 'saveorder':
		saveOrder($cid);
		break;
  case 'accesspublic':
	case 'accessregistered':
	case 'accessspecial':
		accessMenu( intval( $cid[0] ), $task, $option, 'extend_fields' );
		break;
	case 'extend_fields':
		showFields( $option );
		break;
	case 'new':
		editUser( 0, $option);
		break;
	case 'edit':
		editUser( intval( $cid[0] ), $option );
		break;
	case 'editA':
		editUser( mosgetparam($_REQUEST, 'id'), $option );
		break;
	case 'save':
	case 'apply':
		// check to see if functionality restricted for use as demo site
		if ( $_VERSION->RESTRICT == 1 ) {
			mosRedirect( 'index2.php?mosmsg=Functionality Restricted' );
		} else {
			saveUser( $task );
		}
		break;
	case 'remove':
		$msg=removeUsers( $cid, $option );
		mosRedirect( 'index'.(mosGetParam($_REQUEST,'previous_task')=='check_email'? '3' : '2' ).'.php?option='.$option.(mosGetParam($_REQUEST,'previous_task')=='check_email'? '&task=check_email' : '' ), $msg );
		break;
	case 'block':
		// check to see if functionality restricted for use as demo site
		if ( $_VERSION->RESTRICT == 1 ) {
			mosRedirect( 'index2.php?mosmsg=Functionality Restricted' );
		} else {
			changeUserBlock( $cid, 1, $option );
		}
		break;
	case 'unblock':
		changeUserBlock( $cid, 0, $option );
		break;
	case 'logout':
		logoutUser( $cid, $option, $task );
		break;
	case 'flogout':
		logoutUser( $id, $option, $task );
		break;
	case 'cancel':
		cancelUser( $option );
		break;
	case 'contact':
		$contact_id = mosGetParam( $_POST, 'contact_id', '' );
		mosRedirect( 'index2.php?option=com_contact&task=editA&id='. $contact_id );
		break;
	case 'moveUsers':
		moveUsers( $cid, $option );
		break;
	case 'buy_juser_pro':
		HTML_JUser::message_page();
		break;
	case 'empty_task':
		$task=$TempTask;
		break;
  case 'show_users':
	default:
		showUsers( $option );
		break;
}
function JUserProSourcePath($task_)
{
	global $mosConfig_absolute_path;
	if( file_exists ( $mosConfig_absolute_path ."/administrator/components/com_juser/admin.juser.pro.php" ) )
		{print "index2.php?option=com_juser&task=".$task_;}
	else{print "index2.php?option=com_juser&task=buy_juser_pro";}
}
function condition_cell($field)
{
	$conditions='';
	if(mosgetparam($_POST,'show_field_'. $field->field_id)=='show')
	{
		if( $field->type == 'select' || $field->type == 'radio' || $field->type == 'checkbox' )
		{
			$values_arr=$_POST['filter_field_'.$field->field_id];
			if(count($values_arr) > 0)
			{
				$i=0;
				$tt=0;
				$conditions.= " AND (";
				foreach(explode("\n",str_replace("\r",'',$field->uvalues)) as $field_value)
				{
					if($values_arr[$i])
					{
						$conditions.= $tt >0 ? ' OR ': '';
						$conditions.= $field->type == 'checkbox' ? " `field_".$field->field_id."` like '%".$field_value."%'" : " `field_".$field->field_id."` like '%".$field_value."%'";
						$tt++;
					}
					$i++;
				}
				$conditions.=" ) ";
			}
		}
		else if( $field->type == 'date' )
		{
			$value = mosgetparam($_POST,'filter_field_'.$field->field_id);
			$sign  = $_POST['sign_field_'.$field->field_id];
			if($value && $sign){
				$conditions.= " AND `field_".$field->field_id."` ". $sign ." '".$value."'";
			}
		}
		else if( $field->type == 'text' || $field->type == 'textaria' )
		{
			$value = mosgetparam($_POST,'filter_field_'.$field->field_id);
			if($value){
				$conditions.= " AND `field_".$field->field_id."` REGEXP '".$value."'";
			}
		}
	}
	return $conditions;
}
function export_execute($ext_fields)
{
    $option = 'com_juser';
	global $mainframe, $database, $mosConfig_absolute_path, $mosConfig_live_site, $mosConfig_list_limit;
    $limit 			= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
	$limitstart 	= intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );

	$additional_sql_fields = '';
	$conditions_having = "\n HAVING 1 ";
	$conditions_where =  "\n WHERE 1 ";
  $sql_limit="\n LIMIT ".$limitstart.",".$limit;

	if(isset($_POST['serial_post'])){
      $_POST = array_merge($_POST, unserialize(stripslashes($_POST['serial_post'])));
    }
      
	if(mosgetparam($_POST,'user_active')!='Both'){
			$conditions_where.= " AND u.block = '".mosgetparam($_POST,'user_active')."'";
	}
	$conditions_where.=mosgetparam($_POST,'from_date') ? " AND u.registerDate >= '".mosgetparam($_POST,'from_date')."'" : '';
	$conditions_where.=mosgetparam($_POST,'to_date') ? " AND u.registerDate <= '".mosgetparam($_POST,'to_date')."'" : '';
	foreach($ext_fields as $field)
	{
		if($field->type=='file'){
			$path=stripslashes(JEConfig::get('general.uploaded_file_directory'));
			$path=str_replace('\\','/',$path);
			$path=str_replace($mosConfig_absolute_path,$mosConfig_live_site,$path);
			$additional_sql_fields .= "\n, IF((SELECT `uvalue` FROM `#__users_extended_data`"
									. "\n WHERE `user_id` = u.id AND `field_id` = '".$field->field_id."')<>'',concat('".$path."',(SELECT `uvalue` FROM `#__users_extended_data`"
									. "\n WHERE `user_id` = u.id AND `field_id` = '".$field->field_id."')),'') as `field_".$field->field_id."`";
		}
		else{
			$additional_sql_fields .= "\n, (SELECT `uvalue` FROM `#__users_extended_data`"
									. "\n WHERE `user_id` = u.id AND `field_id` = '".$field->field_id."') as `field_".$field->field_id."`";
		}
		$conditions_having .= "\n ".condition_cell($field);
	}
	$query = "SELECT u.id ,u.name, u.username, u.email, u.registerDate, u.block "
			. $additional_sql_fields
			. "\n FROM `#__users` as `u`"
			. $conditions_where
			. $conditions_having
      . $sql_limit
			;
	//print'<div align="left" style="color:#990099"><pre>';print str_replace("#_",'jos',$query);print'</pre></div>';exit;
	$database->setQuery( $query );
	$rows = $database->loadAssocList();


	//$query = "SELECT count(`id`) FROM #__users as `u` ".$conditions_where;
	$query = "SELECT u.id "
			. $additional_sql_fields
			. "\n FROM `#__users` as `u`"
			. $conditions_where
			. $conditions_having;
	$database->setQuery( $query );
	$total_user = $database->loadObjectList();


	require_once( $GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php' );
	//print "mosPageNav( $total, $limitstart, $limit )";
  $pageNav = new mosPageNav( count($total_user), $limitstart, $limit );



	HTML_JUser::export_execute($rows,$ext_fields,$pageNav);
	/*print'<div align="left" style="color:#990099"><pre>';print str_replace("#_",'jos',$query);print'</pre></div>';
	print'<div align="left" style="color:#008000"><pre>';print_r($rows);print'</pre></div>';
	print'<div align="left" style="color:#0000ff"><pre>';print_r($_POST);print'</pre></div>';*/
}
function saveOrder($cid)
{
	global $database;

	$total		= count( $cid );
	$order 		= mosgetparam($_POST, 'order' , 'array');

	$row 		= new mosJUser( $database );
	$conditions = array();

	// update ordering values
	for( $i=0; $i < $total; $i++ ) {
		$row->load( (int) $cid[$i] );
		if ($row->ordering != $order[$i]) {
			$row->ordering = $order[$i];
			if (!$row->store()) {
				echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
				exit();
			} // if
			// remember to updateOrder this group
			$condition = "catid = '$row->catid'";
			$found = false;
			foreach ( $conditions as $cond )
				if ($cond[1]==$condition) {
					$found = true;
					break;
				} // if
			if (!$found) $conditions[] = array($row->id, $condition);
		} // if
	} // for

	// execute updateOrder for each group
	foreach ( $conditions as $cond ) {
		$row->load( $cond[0] );
		$row->updateOrder( $cond[1] );
	} // foreach

	mosCache::cleanCache( 'com_content' );

	$msg 	= 'New order is saved';

	mosRedirect( 'index2.php?option=com_juser&task=extend_fields', $msg );
}

function orderField( $fid, $inc, $option ) {
	global $database;

		$query = "SELECT #__extending_field_list.*"
			. "\n FROM `#__extending_field_list`"
			. "\n WHERE #__extending_field_list.id = ".$fid;
		$database->setQuery( $query );
		$field = $database->loadObjectList();

		$query = "UPDATE #__extending_field_list"
		. "\n SET `ordering` = " . ($field[0]->ordering+$inc)
		. "\n WHERE id = " . $fid;
		$database->setQuery( $query );
		$database->query();

		$query = "UPDATE #__extending_field_list "
		. "\n SET `ordering` = " . ($field[0]->ordering)
		. "\n WHERE `ordering` = " . ($field[0]->ordering+$inc) . " AND `catid` = ". $field[0]->catid . " AND `id` != " . $field[0]->id;
		$database->setQuery( $query );
		$database->query();

		mosRedirect( 'index2.php?option=com_juser&task=extend_fields' );
}

function editField($mode='')
{
	global $database;
  if(!$mode){
  	$query = "SELECT #__extending_field_list.*"
  		. "\n FROM `#__extending_field_list`"
  		. "\n where #__extending_field_list.id = ".mosGetParam($_GET, 'field_id');
  	$database->setQuery( $query );
  	$field = $database->loadObjectList();
	}

	$query = "SELECT * FROM `#__categories` where `section` = 'com_extending_field_list'";
	$database->setQuery( $query );
	$categories= $database->loadObjectList();

  $fields_by_cat = array();
	foreach($categories as $category){
   $query = "SELECT *"
   		. "\n FROM `#__extending_field_list`"
   	  . "\n WHERE `catid` = ".$category->id
   	  . "\n ORDER by `ordering`";
   $database->setQuery( $query );
   $fields_ = $database->loadObjectList();
   $i=0;
   foreach($fields_ as $field_)
   {
     //$fields_by_cat[$category->id][$i]['id'] = $field_->id;
     $fields_by_cat[$category->id][$i]['title'] = str_limit($field_->title, 30);
     $fields_by_cat[$category->id][$i]['ordering'] = $field_->ordering;
     $i++;
   }
  }
  if($mode == 'new'){
   HTML_JUser::editField( array(),$categories, $fields_by_cat, mosGetParam( $_REQUEST, 'suggestion', '' ) );}
  else{
	 HTML_JUser::editField($field[0], $categories, $fields_by_cat);}
}

function accessMenu( $uid, $access, $option, $task ) {
	global $database;

	switch ( $access ) {
		case 'accesspublic':
			$access = 0;
			break;

		case 'accessregistered':
			$access = 1;
			break;

		case 'accessspecial':
			$access = 2;
			break;
	}

  $query = "UPDATE #__extending_field_list "
		. "\n SET `access` = " . $access
		. "\n WHERE `id` = " . $uid;
  $database->setQuery( $query );
  $database->query();

	mosRedirect( 'index2.php?option=com_juser&task='. $task );
}
function showFields($option)
{
	global $database, $mainframe, $mosConfig_list_limit;

	$limit 			= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
	$limitstart 	= intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );


	$query = "SELECT field_list.* , #__categories.name AS cat_name,g.name AS groupname, count(user_data.user_id) as `users_count`"
				. "\n FROM #__extending_field_list as `field_list`"
        . "\n LEFT JOIN #__groups AS g ON g.id = field_list.access"
				. "\n LEFT JOIN #__categories ON #__categories.id = field_list.catid"
				. "\n LEFT JOIN #__users_extended_data as user_data ON user_data.field_id = field_list.id and user_data.uvalue <> ''"
				. "\n group by field_list.id"
				. "\n ORDER BY #__categories.ordering, field_list.ordering"
				. "\n limit ".$limitstart.', '.$limit;
				//print'$query:<pre>'.str_replace('#__','jos_',$query).'</pre>';exit;
	$database->setQuery( $query );
	$ext_fields = $database->loadObjectList();
	//print str_replace('#_', 'jos', $query);exit;
	$query = "SELECT count(`id`) FROM #__extending_field_list";
	$database->setQuery( $query );
	$total = $database->loadResult();

	require_once( $GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php' );
	$pageNav = new mosPageNav( $total, $limitstart, $limit );

	HTML_JUser::showFields( $ext_fields, $option, $pageNav);
}

function showUsers( $option, $simple = false ) {
	global $database, $mainframe, $my, $acl, $mosConfig_list_limit;
    $option = 'com_juser';
	$filter_type	= $mainframe->getUserStateFromRequest( "filter_type{$option}", 'filter_type', 0 );
	$filter_logged	= intval( $mainframe->getUserStateFromRequest( "filter_logged{$option}", 'filter_logged', 0 ) );
	$limit 			= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
	$limitstart 	= intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );
	$search			= $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
	$where 			= array();

	if ( $filter_type ) {
		if ( $filter_type == 29 || $filter_type == 30) {
			$fgids = $acl->get_group_children( (int) $filter_type , 'ARO', 'RECURSE' );
			mosArrayToInts( $fgids );
			if (is_array( $fgids ) && count( $fgids ) > 0) {
				$where[] = "( a.gid = " . implode(" OR a.gid = ", $fgids) . " )";
			}
		} else {
			if($filter_type>0) $where[] = "a.gid = '". (int) $filter_type."'";
		}
	}

	// exclude any child group id's for this user
	$pgids = $acl->get_group_children( $my->gid, 'ARO', 'RECURSE' );
	if( $my->gid != 23 && $my->gid != 24 && $my->gid != 25) {
		$pgids = array_push($pgids, "23", "24", "25");
	}

	mosArrayToInts( $pgids );
	if (is_array( $pgids ) && count( $pgids ) > 0) {
		$where[] = '( a.gid != ' . implode( ' OR a.gid != ', $pgids ) . ' )';
	}

	$query = "SELECT COUNT(a.id)"
	. "\n FROM #__users AS a";

	if ($filter_logged == 1 || $filter_logged == 2) {
		$query .= "\n INNER JOIN #__session AS s ON s.userid = a.id";
	}
	$query = queryWithFlters((count( $where)>0 ? ' AND '.implode( " AND ", $where ):""), true);
	$database->setQuery( $query );
	$total = $database->loadResult();

	require_once( $GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php' );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );

	$query = queryWithFlters((count( $where)>0 ? ' AND '.implode( " AND ", $where ):""));
	$database->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
	$rows = $database->loadObjectList();

	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	$template = 'SELECT COUNT(s.userid) FROM #__session AS s WHERE s.userid = ';
	$n = count( $rows );
	for ($i = 0; $i < $n; $i++) {
		$row = &$rows[$i];
		$query = $template . (int) $row->id;
		$database->setQuery( $query );
		$row->loggedin = $database->loadResult();
	}

	// get list of Groups for dropdown filter
	$query = "SELECT group_id AS value, name AS text"
	. "\n FROM #__core_acl_aro_groups"
	. "\n WHERE name != 'ROOT'"
	. "\n AND name != 'USERS'"
	;
	if (is_array( $pgids ) && count( $pgids ) > 0) {
		$query .= "\n AND ( group_id != " . implode( ' OR group_id != ', $pgids ) . " )";
	}
	$types[] = mosHTML::makeOption( '0', '- Select Group -' );
	$database->setQuery( $query );
	$types = array_merge( $types, $database->loadObjectList() );
	$lists['type'] = mosHTML::selectList( $types, 'filter_type', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', "$filter_type" );
	$lists['grouptype'] = mosHTML::selectList( $types, 'group_type', 'class="inputbox" size="1" onchange="javascript:submitbutton(\'moveUsers\');"', 'value', 'text', '' );

	// get list of Log Status for dropdown filter
	$logged[] = mosHTML::makeOption( 0, '- Select Log Status - ');
	$logged[] = mosHTML::makeOption( 1, 'Logged In');
	$lists['logged'] = mosHTML::selectList( $logged, 'filter_logged', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', "$filter_logged" );
	// get list of Log Status for dropdown filter

	$database->setQuery("SELECT * FROM `#__extending_field_list` WHERE `search_by_this_field` = 1 AND `published` = 1");
  $fields_for_filter = $database->loadObjectList();
  if(is_array($fields_for_filter) && count($fields_for_filter)>0){
    foreach($fields_for_filter as $field){
      if($field->type == 'select' || $field->type == 'radio' || $field->type == 'checkbox'){
        unset($temp_list);
        $temp_list[] = mosHTML::makeOption( '', '- Select '.str_limit($field->title,30).' - ');

        $values_for_filter = explode("\n",str_replace("\r", "", $field->uvalues));
        foreach($values_for_filter as $value){
          $temp_list[] = mosHTML::makeOption( $value, str_limit($value,30));
        }
        $lists['additional_filters'][] = mosHTML::selectList( $temp_list, $field->id.'filter_field', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', mosGetParam($_REQUEST, $field->id.'filter_field') );
      }
    }
  }

	if( !$simple ){
		HTML_JUser::showUsers( $rows, $pageNav, $search, $option, $lists );
	}
	else
	{
		HTML_JUser::ShowUsersForm( $rows, $pageNav, true );
	}

}

function editUser( $uid='0', $option='juser' ) {
	global $database, $my, $acl, $mainframe;

	$msg = checkUserPermissions( array($uid), "edit", true );
	if ($msg) {
		echo "<script type=\"text/javascript\"> alert('".$msg."'); window.history.go(-1);</script>\n";
		exit;
	}

	$row = new mosUser( $database );
	// load the row from the db table
	$row->load( (int)$uid );

	if ( $uid ) {
		$query = "SELECT *"
		. "\n FROM #__contact_details"
		. "\n WHERE user_id = " . (int) $row->id
		;
		$database->setQuery( $query );
		$contact = $database->loadObjectList();

		$row->name = trim( $row->name );
		$row->email = trim( $row->email );
		$row->username = trim( $row->username );
		$row->password = trim( $row->password );

	} else {
		$contact 	= NULL;
		$row->block = 0;
	}

	if ( ( $my->gid != 25 ) && ( $row->gid == 25 ) ) {
		mosRedirect( 'index2.php?option=com_juser', _NOT_AUTH );
	}

	if ( $my->gid != 25 && $row->gid == 25 ) {
		$lists['gid'] = '<input type="hidden" name="gid" value="'. $my->gid .'" /><strong>Super Administrator</strong>';
	} else if ( $my->gid == 24 && $row->gid == 24 ) {
		$lists['gid'] = '<input type="hidden" name="gid" value="'. $my->gid .'" /><strong>Administrator</strong>';
	} else {
		$my_groups = $acl->get_object_groups( 'users', $my->id, 'ARO' );
		if (is_array( $my_groups ) && count( $my_groups ) > 0) {
			$ex_groups = $acl->get_group_children( $my_groups[0], 'ARO', 'RECURSE' );
		} else {
			$ex_groups = array();
		}

		$gtree = $acl->get_group_children_tree( null, 'USERS', false );

		$i = 0;
		while ($i < count( $gtree )) {
			if (in_array( $gtree[$i]->value, $ex_groups )) {
				array_splice( $gtree, $i, 1 );
			} else {
				$i++;
			}
		}

		$lists['gid'] 		= mosHTML::selectList( $gtree, 'gid', 'size="10"', 'value', 'text', $row->gid );
	}

	$lists['block'] 		= mosHTML::yesnoRadioList( 'block', 'class="inputbox" size="1"', $row->block );
	$lists['sendEmail'] 	= mosHTML::yesnoRadioList( 'sendEmail', 'class="inputbox" size="1"', $row->sendEmail );

	$file 	= $mainframe->getPath( 'com_xml', 'com_users' );
	$params =& new mosUserParameters( $row->params, $file, 'component' );

		$query = "SELECT #__extending_field_list. * , #__extending_field_list.id as field_id, #__categories.title as cat_title, #__users_extended_data.uvalue as `uvalue`"
		. "\n FROM #__extending_field_list"
		. "\n LEFT JOIN #__users_extended_data ON #__extending_field_list.id = #__users_extended_data.field_id"
		. "\n AND #__users_extended_data.user_id = " . (int) $row->id
		. "\n LEFT JOIN #__categories ON #__categories.id = #__extending_field_list.catid"
		. "\n ORDER BY #__categories.ordering, #__extending_field_list.ordering"
		;
	$database->setQuery( $query );
	$ext_row = $database->loadObjectList();
	/*print'$field<pre>'.str_replace('#__','jos_',$query).'</pre>';
  print'$field<pre>';print_r($ext_row);print'</pre>';
	exit;*/
	HTML_JUser::editUser( $row, $ext_row, $contact, $lists, $option, $uid, $params );
}

function saveUser( $task ) {
	global $database, $my, $acl;
	global $mosConfig_live_site, $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_sitename;

	$userIdPosted = mosGetParam($_POST, 'id');


	if ($userIdPosted) {
		$msg = checkUserPermissions( array($userIdPosted), 'save', in_array($my->gid, array(24, 25)) );
		if ($msg) {
			echo "<script type=\"text/javascript\"> alert('".$msg."'); window.history.go(-1);</script>\n";
			exit;
		}
	}


	$row = new mosUser( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	$row->name = trim( $row->name );
	$row->email = trim( $row->email );
	$row->username = trim( $row->username );

	$row->id 	= (int) $row->id;
	$row->gid 	= (int) $row->gid;

	$isNew 	= !$row->id;
	$pwd 	= '';

	if ($isNew) {
		if ($row->password == '') {
			$pwd 			= mosMakePassword();
			$row->password 	= md5( $pwd );
		} else {
			$pwd 			= trim( $row->password );
			$row->password 	= md5( trim( $row->password ) );
		}
		$row->registerDate 	= date( 'Y-m-d H:i:s' );
	} else {
		$original = new mosUser( $database );
		$original->load( (int)$row->id );

		if ($row->password == '') {
			$row->password = null;
		} else {
			$row->password = md5( trim( $row->password ) );
		}

		if ( $row->gid != $original->gid ) {
			if ( $original->gid == 25 ) {
				$query = "SELECT COUNT( id )"
				. "\n FROM #__users"
				. "\n WHERE gid = 25"
				. "\n AND block = 0"
				;
				$database->setQuery( $query );
				$count = $database->loadResult();

				if ( $count <= 1 ) {
					echo "<script> alert('You cannot change this users Group as it is the only active Super Administrator for your site'); window.history.go(-1); </script>\n";
					exit();
				}
			}

			$user_group = strtolower( $acl->get_group_name( $original->gid, 'ARO' ) );
			if (( $user_group == 'super administrator' && $my->gid != 25) ) {
				echo "<script> alert('You cannot change this users Group as you are not a Super Administrator for your site'); window.history.go(-1); </script>\n";
				exit();
			} else if ( $my->gid == 24 && $original->gid == 24 ) {
				echo "<script> alert('You cannot change the Group of another Administrator as you are not a Super Administrator for your site'); window.history.go(-1); </script>\n";
				exit();
			}
		}
	}

	if (!in_array($row->gid,getGIDSChildren($my->gid))) {
			echo "<script> alert('You cannot create a user with this user Group level, only Super Administrators have this ability'); window.history.go(-1); </script>\n";
		exit();
	}

	$query = "SELECT name"
	. "\n FROM #__core_acl_aro_groups"
	. "\n WHERE group_id = " . (int) $row->gid
	;
	$database->setQuery( $query );
	$usertype = $database->loadResult();
	$row->usertype = $usertype;

	$params = mosGetParam( $_POST, 'params', '' );
	if (is_array( $params )) {
		$txt = array();
		foreach ( $params as $k=>$v) {
			$txt[] = "$k=$v";
		}
		$row->params = implode( "\n", $txt );
	}

	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	$row->checkin();

	if ( $my->id == $row->id ) {
		$_SESSION['session_user_params']= $row->params;
		session_write_close();
	}

	if (!$isNew) {
		$query = "SELECT aro_id"
		. "\n FROM #__core_acl_aro"
		. "\n WHERE value = " . (int) $row->id
		;
		$database->setQuery( $query );
		$aro_id = $database->loadResult();

		$query = "UPDATE #__core_acl_groups_aro_map"
		. "\n SET group_id = " . (int) $row->gid
		. "\n WHERE aro_id = " . (int) $aro_id
		;
		$database->setQuery( $query );
		$database->query() or die( $database->stderr() );
	}

	if ($isNew) {
		$query = "SELECT email"
		. "\n FROM #__users"
		. "\n WHERE id = " . (int) $my->id
		;
		$database->setQuery( $query );
		$adminEmail = $database->loadResult();

		$subject = _NEW_USER_MESSAGE_SUBJECT;
		$message = sprintf ( _NEW_USER_MESSAGE, $row->name, $mosConfig_sitename, $mosConfig_live_site, $row->username, $pwd );

		if ($mosConfig_mailfrom != "" && $mosConfig_fromname != "") {
			$adminName 	= $mosConfig_fromname;
			$adminEmail = $mosConfig_mailfrom;
		} else {
			$query = "SELECT name, email"
			. "\n FROM #__users"
			. "\n WHERE gid = 25"
			;
			$database->setQuery( $query );
			$admins = $database->loadObjectList();
			$admin 		= $admins[0];
			$adminName 	= $admin->name;
			$adminEmail = $admin->email;
		}

		mosMail( $adminEmail, $adminName, $row->email, $subject, $message );
	}

	if (!$isNew) {
		if ( $original->gid != $row->gid ) {
			logoutUser( $row->id, 'com_users', 'change' );
		}
	}

	$query = "SELECT * FROM #__users where `name`='".mosGetParam($_POST, 'name')."' and `username`='".mosGetParam($_POST, 'username')."' and `email`='".mosGetParam($_POST, 'email')."'";
	$database->setQuery( $query );
	$current_user = $database->loadObjectList();
	JUser::saveUser_ext($current_user[0]->id);

	//synchronize dublicate user data
  $database->setQuery("SELECT `id` FROM  `#__juser_integration` WHERE  `published` = 1 AND `export_status` = 1");
  $components = $database->loadObjectList();
  foreach($components as $component)
  {
	  /*$xml = new integration_XML ($component->id);
    $synchronize = new synchronizeUsersData($xml);
    $synchronize->updateExteriorUser($current_user[0]->id);*/
	  $synchronize = require_integration($component->id);
    //$synchronize = new comIntegration ( $component->id );
    $synchronize->updateExteriorUser( $current_user[0]->id );
  }
	//synchronize dublicate user data(end)

	switch ( $task ) {
		case 'apply':
			$msg = 'Successfully Saved changes to User: '. $row->name;
			mosRedirect( 'index2.php?option=com_juser&task=editA&hidemainmenu=1&id='. $row->id, $msg );
			break;

		case 'save':
		default:
			$msg = 'Successfully Saved User: '. $row->name;
			mosRedirect( 'index2.php?option=com_juser', $msg );
			break;
	}
}

function cancelUser( $option ) {
	mosRedirect( 'index2.php?option='. $option .'&task=view' );
}

function removeUsers( $cid, $option ) {
	global $database, $acl, $my;

	if (!is_array( $cid ) || count( $cid ) < 1) {
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}

	$msg = checkUserPermissions( $cid, 'delete' );

	if ( !$msg && count( $cid ) ) {
		$obj = new mosUser( $database );
		foreach ($cid as $id) {
			$obj->load( $id );
			$count = 2;
			if ( $obj->gid == 25 ) {
				$query = "SELECT COUNT( id )"
				. "\n FROM #__users"
				. "\n WHERE gid = 25"
				. "\n AND block = 0"
				;
				$database->setQuery( $query );
				$count = $database->loadResult();
			}

			if ( $count <= 1 && $obj->gid == 25 ) {
				$msg = "You cannot delete this Super Administrator as it is the only active Super Administrator for your site";
			} else {
				$obj->delete( $id );

				$query = "DELETE FROM #__users_extended_data"
 						. "\n WHERE `user_id` = ".$id;
 				$database->setQuery( $query );
				$database->query();

				$msg = $obj->getError();

				logoutUser( $id, 'com_users', 'remove' );
				//synchronize dublicate delete
    		  $database->setQuery("SELECT `id` FROM  `#__juser_integration` WHERE  published` = 1 AND `export_status` = 1");
    		  $components = $database->loadObjectList();
    		  foreach($components as $component)
    		  {
      		  /*$xml = new integration_XML ($component->id);
            $synchronize = new synchronizeUsersData($xml);
            $synchronize->deleteExteriorUser($id);*/
      		  $synchronize = require_integration($component->id);
      		  //$synchronize = new comIntegration ( $component->id );
            $synchronize->deleteExteriorUser( $id );
    		  }
        //synchronize dublicate delete(end)
			}
		}
	}
	return $msg;
}

function changeUserBlock( $cid=null, $block=1, $option ) {
	global $database;

	$action = $block ? 'block' : 'unblock';

	if (count( $cid ) < 1) {
		echo "<script type=\"text/javascript\"> alert('Select an item to $action'); window.history.go(-1);</script>\n";
		exit;
	}

	$msg = checkUserPermissions( $cid, $action );
	if ($msg) {
		echo "<script type=\"text/javascript\"> alert('".$msg."'); window.history.go(-1);</script>\n";
		exit;
	}

	mosArrayToInts( $cid );
	$cids = 'id=' . implode( ' OR id=', $cid );

	$query = "UPDATE #__users"
	. "\n SET block = " . (int) $block
	. "\n WHERE ( $cids )"
	;
	$database->setQuery( $query );
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}

	if ( $block == 1 ) {
		foreach( $cid as $id ) {
			logoutUser( $id, 'com_users', 'block' );
		}
	}

	mosRedirect( 'index2.php?option='. $option );
}

function logoutUser( $cid=null, $option, $task ) {
	global $database, $my;

	if ( is_array( $cid ) ) {
		if (count( $cid ) < 1) {
			mosRedirect( 'index2.php?option='. $option, 'Please select a user' );
		}

		foreach( $cid as $cidA ) {
			$temp = new mosUser( $database );
			$temp->load( $cidA );

			if ( !( $my->gid == 24 && $temp->gid == 25 ) ) {
				$id[] = $cidA;
			}
		}
		mosArrayToInts( $cid );
		$ids = 'userid=' . implode( ' OR userid=', $cid );
	} else {
		$temp = new mosUser( $database );
		$temp->load( $cid );

		if ( $my->gid == 24 && $temp->gid == 25 ) {
			echo "<script> alert('You cannot log out a Super Administrator'); window.history.go(-1); </script>\n";
			exit();
		}
		$ids = 'userid=' . (int) $cid;
	}

	$query = "DELETE FROM #__session"
 	. "\n WHERE ( $ids )"
 	;
	$database->setQuery( $query );
	$database->query();

	switch ( $task ) {
		case 'flogout':
			mosRedirect( 'index2.php', $database->getErrorMsg() );
			break;

		case 'remove':
		case 'block':
		case 'change':
			return;
			break;

		default:
			mosRedirect( 'index2.php?option='. $option, $database->getErrorMsg() );
			break;
	}
}

function checkUserPermissions( $cid, $actionName, $allowActionToMyself = false ) {
	global $database, $acl, $my;

	$msg = null;
	if (is_array( $cid ) && count( $cid )) {
		$obj = new mosUser( $database );
		foreach ($cid as $id) {
			if ( $id != 0 ) {
				$obj->load( $id );
				$groups 	= $acl->get_object_groups( 'users', $id, 'ARO' );
				$this_group = strtolower( $acl->get_group_name( $groups[0], 'ARO' ) );
			} else {
				$this_group = 'Registered';
				$obj->gid 	= $acl->get_group_id( $this_group, 'ARO' );
			}

			if ( !$allowActionToMyself && $id == $my->id ){
 				$msg .= 'You cannot '. $actionName .' Yourself!';
 			} else if (($obj->gid == $my->gid && !in_array($my->gid, array(24, 25))) || ($obj->gid && !in_array($obj->gid,getGIDSChildren($my->gid)))) {
				$msg .= 'You cannot '. $actionName .' a `'. $this_group .'`. Only higher-level users have this power. ';
			}
		}
	}

	return $msg;
}

function getGIDSChildren($gid) {
	global $database;

	$standardlist = array(-2,);

	$query = "SELECT g1.group_id, g1.name"
	."\n FROM #__core_acl_aro_groups g1"
	."\n LEFT JOIN #__core_acl_aro_groups g2 ON g2.lft >= g1.lft"
	."\n WHERE g2.group_id = " . (int) $gid
	."\n ORDER BY g1.name"
	;
	$database->setQuery( $query );
	$array = $database->loadResultArray();

	if( $gid > 0 ) {
		$standardlist[]=-1;
	}
	$array = array_merge($array,$standardlist);

	return $array;
}

function getGIDSParents($gid) {
	global $database;

  	$query = "SELECT g1.group_id, g1.name"
	."\n FROM #__core_acl_aro_groups g1"
	."\n LEFT JOIN #__core_acl_aro_groups g2 ON g2.lft <= g1.lft"
	."\n WHERE g2.group_id = " . (int) $gid
	."\n ORDER BY g1.name"
	;
   	$database->setQuery( $query );
	$array = $database->loadResultArray();

	return $array;
}

function moveUsers( $cid, $option ) {
	global $database, $mainframe, $acl, $my;

	if (!is_array( $cid ) || count( $cid ) < 1) {
		echo "<script> alert('Select an item to move'); window.history.go(-1);</script>\n";
		exit;
	}

	$msg = checkUserPermissions( $cid, 'move' );

	if ( !$msg && count( $cid ) ) {
		$group_type	= intval($mainframe->getUserStateFromRequest( "group_type{$option}", 'group_type', 0 ));
		$query = "SELECT name"
		. "\n FROM #__core_acl_aro_groups"
		. "\n WHERE group_id = " . (int) $group_type
		;
		$database->setQuery( $query );
		$usertype = $database->loadResult();

		$obj = new mosUser( $database );
		mosArrayToInts( $cid );
		foreach ($cid as $id) {
			$obj->load( $id );
			$count = 2;
			if ( $obj->gid == 25 ) {
				$query = "SELECT COUNT( id )"
				. "\n FROM #__users"
				. "\n WHERE gid = 25"
				. "\n AND block = 0"
				;
				$database->setQuery( $query );
				$count = $database->loadResult();
			}

			if ( $count <= 1 && $obj->gid == 25 ) {
				$msg = "You cannot move this Super Administrator as it is the only active Super Administrator for your site";
			} else {
				$query = "UPDATE #__users"
				. "\n SET gid = " . (int) $group_type . ", usertype = " . $database->Quote( $usertype )
				. "\n WHERE id = " . (int) $id
				;
				$database->setQuery( $query );
				$database->query();

				$query = "SELECT aro_id"
				. "\n FROM #__core_acl_aro"
				. "\n WHERE value = " . (int) $id
				;
				$database->setQuery( $query );
				$aro_id = $database->loadResult();

				$query = "UPDATE #__core_acl_groups_aro_map"
				. "\n SET group_id = " . (int) $group_type
				. "\n WHERE aro_id = " . (int) $aro_id
				;
				$database->setQuery( $query );
				$database->query();

				logoutUser( $id, 'com_users', 'change' );
			}
		}
	}

	mosRedirect( 'index2.php?option='. $option, $msg );
}

if($task != "report_for_print" &&$task != 'export_file')
{
?>
<div style="clear:both;"></div><br>
		Copyright &copy; 2007 JoomlaEquipment<br>
		Support Email: <a href="mailto:support@joomlaequipment.com">support@joomlaequipment.com</a>
	<?php
}
?>
